package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.dto.LikedTimesDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author Yandel
 * @since 2025-05-19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper rabbitMqHelper;
    private final StringRedisTemplate  redisTemplate;
    @Override
    public void addLikeRecord(LikeRecordFormDTO recordDTO) {
        //获取当前用户id
        Long userId = UserContext.getUser();
        // 1.基于前端的参数，判断是执行点赞还是取消点赞
        boolean Flag = recordDTO.getLiked() ? like(recordDTO,userId) : unlike(recordDTO,userId);
        // 2.判断是否执行成功，如果失败，则直接结束
        if (!Flag) {
            return;
        }
        // 3.如果执行成功，统计点赞总数
//        Integer likesTotals = this.lambdaQuery()
//                .eq(LikedRecord::getBizId, recordDTO.getBizId())
//                .count();

        //基于redis实现统计点赞数量
        //拼接Key     likes:set:biz:评论id
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + recordDTO.getBizId();
        Long totalLikesNums = redisTemplate.opsForSet().size(key);
        if (totalLikesNums == null) {
            return;
        }

        //4、采用zset实现点赞数量统计      likes:times:type:QA
        String bizTypeTotalLikeKey = RedisConstants.LIKES_COUNT_KEY_PREFIX + recordDTO.getBizType();
       redisTemplate.opsForZSet().add(bizTypeTotalLikeKey, recordDTO.getBizId().toString(), totalLikesNums);

/*        // 4.发送MQ通知
        String routingKey  = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, "QA");
//        LikedTimesDTO msg = LikedTimesDTO.of(recordDTO.getBizId(), likesTotals);
        LikeTimesDTO msg = LikeTimesDTO.of(recordDTO.getBizId(), likesTotals);
        log.debug("发送点赞总数消息 消息内容：{}", msg);
        mqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                routingKey,
                msg
        );*/
    }

    private boolean unlike(LikeRecordFormDTO recordDTO,Long userId){
        //拼接key
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + recordDTO.getBizId();
        //从set结构中删除当前userId
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());
        return result != null && result > 0;

       /* //1.确定是取消点赞
        return this.remove(Wrappers.<LikedRecord>lambdaQuery()
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .eq(LikedRecord::getBizId, recordDTO.getBizId()));*/
    }

    private boolean like(LikeRecordFormDTO recordDTO,Long userId) {
        //基于redis实现点赞
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + recordDTO.getBizId();
        //redisTemplate 往redis 的set结构添加点赞记录
        Long result = redisTemplate.opsForSet().add(key, userId.toString());
        return result != null && result > 0;


/*        Long userId = UserContext.getUser();
        //1.查询点赞记录
        Integer count = this.lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizId, recordDTO.getBizId())
                .count();
        // 2.判断是否存在，如果已经存在，直接结束
        if (count > 0){
            return false;
        }
        // 3.如果不存在，直接新增
        LikedRecord record = new LikedRecord();
        record.setUserId(userId);
        record.setBizId(recordDTO.getBizId());
        record.setBizType(recordDTO.getBizType());
        this.save(record);
        return true;*/
    }

    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        //基于redis实现

        //版本三：
        // 1.获取登录用户id
        Long userId = UserContext.getUser();
        // 2.查询点赞状态
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });
        // 3.返回结果
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(bizIds::get)// 用角标i取bizIds中的对应数据，就是点赞过的id
                .collect(Collectors.toSet());// 收集

        //版本二：
   /*     //1、获取用户id
        Long userId = UserContext.getUser();
        if (CollUtils.isEmpty(bizIds)){
            return CollUtils.emptySet();
        }
        Set<Long> likedBizIds= new HashSet<>();
        //2、循环bizIds
        for (Long bizId : bizIds) {
            //判断该业务id   的点赞用户集合中是否包含当前用户
            Boolean member = redisTemplate.opsForSet().isMember(RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId, userId.toString());
            if (member) {
                likedBizIds.add(bizId);
            }

        }
        return likedBizIds;*/

        //版本一：
    /*   //1、获取用户id
        Long userId = UserContext.getUser();
        //2、查询点赞记录表
        List<LikedRecord> likedRecordList = this.lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .in(LikedRecord::getBizId, bizIds)
                .list();

        //3、list 转set集合返回
        Set<Long> likedBizIdSet = likedRecordList.stream()
                .map(LikedRecord::getBizId)
                .collect(Collectors.toSet());
        return likedBizIdSet;*/
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        // 拼接key
        String bizTypeTotalLikeKey = RedisConstants.LIKES_COUNT_KEY_PREFIX + bizType;

        List<LikedTimesDTO> list = new ArrayList<>();

        // 从redis的zset结构中取maxBizSize 的业务点赞信息
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(bizTypeTotalLikeKey, maxBizSize);
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String bizId = typedTuple.getValue();//业务id
            Double likedTimes = typedTuple.getScore();//  点赞数量
            if (StringUtils.isBlank(bizId) || likedTimes == null) {
                continue;
            }
            // 封装LikedTimesDTO 消息数据
            LikedTimesDTO msg = LikedTimesDTO.of(Long.valueOf(bizId), likedTimes.intValue());
            list.add(msg);
        }

        // 发送消息到mq
        log.debug("批量发送点赞消息 消息内容{}", list);
        if (CollUtils.isNotEmpty(list)) {
            String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType);
            rabbitMqHelper.send(
                    MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                    routingKey,
                    list);
        }

    }
}
